package ar.com.larctest.providers;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import ar.com.larctest.dbHelper.SQLLARCTESTHelper;
import ar.com.larctest.entities.Work;

public class WorkProvider {
    private static final String TAG = "WorkProvider";

	private static final String DB_COLUMN_0_NAME = "idWork";
	private static final String DB_COLUMN_1_NAME = "description";

	private SQLiteDatabase database;
	private SQLLARCTESTHelper dbHelper;
	private String[] allColumns = {DB_COLUMN_0_NAME, DB_COLUMN_1_NAME};

	public WorkProvider(Context context) {
		dbHelper = SQLLARCTESTHelper.getHelper(context);
		database = dbHelper.getWritableDatabase();
	}

	public Work getWork(Integer idWork)
	{
        Cursor cursor = null;
        Work work = null;

        try
		{
			cursor = database.query(SQLLARCTESTHelper.DB_WORK_TABLE_NAME, allColumns, DB_COLUMN_0_NAME + " = " + idWork, null, null, null, null);
			cursor.moveToFirst();

            work = new Work();
            work.setIdWork(cursor.getInt(0));
            work.setDescription(cursor.getString(1));

			return work;
		}
		catch (Exception e) {
            Log.e(TAG, e.getMessage());
            return work;
		}
        finally {
            if (cursor != null) {
                cursor.close();
            }
        }
	}
	
	public List<Work> getWorks()
    {
        Cursor cursor = null;
		List<Work> lstHumidity = new ArrayList<Work>();

        try
        {
            cursor = database.query(SQLLARCTESTHelper.DB_WORK_TABLE_NAME, allColumns, null, null, null, null, null);
            cursor.moveToFirst();

            while (!cursor.isAfterLast()) {
                Work work = new Work();
                work.setIdWork(cursor.getInt(0));
                work.setDescription(cursor.getString(1));

                lstHumidity.add(work);
                cursor.moveToNext();
            }
            cursor.close();
            return lstHumidity;
        }
        catch (Exception e) {
            Log.e(TAG, e.getMessage());
            return lstHumidity;
        }
        finally {
            if (cursor != null) {
                cursor.close();
            }
        }
	}
}
